from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import os

from process import three,expression,mix
from oss import upload_file_to_oss

app = FastAPI()

process_dict = {}
process_dict["rebuild"] = three
process_dict["expression"] = expression
process_dict['mix'] = mix


origins = [
    "http://localhost:5173",  # 允许的前端地址
    "http://localhost:63342"

]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 文件上传路径
UPLOAD_DIRECTORY = "./static"

if not os.path.exists(UPLOAD_DIRECTORY):
    os.makedirs(UPLOAD_DIRECTORY)

app.mount("/static", StaticFiles(directory=UPLOAD_DIRECTORY), name="static")

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    # 检查文件名是否包含非法字符
    if file.filename == '':
        raise HTTPException(status_code=400, detail="No file selected for uploading")

    # 确保目录存在
    if not os.path.exists(UPLOAD_DIRECTORY):
        os.makedirs(UPLOAD_DIRECTORY)

    # 构建文件的完整路径
    destination = os.path.join(UPLOAD_DIRECTORY, file.filename)

    # 保存文件
    with open(destination, "wb") as buffer:
        content = await file.read()
        buffer.write(content)

    url = upload_file_to_oss(destination)

    return JSONResponse(content={"filename": url}, status_code=200)

@app.get("/process/{file_name}/{process_name}")
def processImage(file_name:str=None,process_name:str=None):
    print(f"{file_name},{process_name}")
    destination = os.path.join(UPLOAD_DIRECTORY, file_name)
    process = process_dict.get(process_name)
    url = upload_file_to_oss(process(destination))
    return JSONResponse(content={"filename": url}, status_code=200)


@app.get("/")
def hello():
    return {"hello":"world"}

# 使用Uvicorn运行应用
if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)